package l1j.server.server.model.damage.hit;

import static l1j.server.server.model.skill.L1SkillId.COUNTER_BARRIER;
import l1j.server.server.model.L1Magic;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.damage.L1Dmg;
import l1j.server.server.utils.Random;

public class L1Hit_Pc_Pc extends L1Hit {
	private L1PcInstance _attacker;

	private L1PcInstance _target;

	private L1PcHit _pcHit;

	public L1Hit_Pc_Pc(L1PcInstance attacker, L1PcInstance target) {
		_attacker = attacker;
		_target = target;
		_pcHit = new L1PcHit(attacker, target);
	}

	public boolean calcHit() {
		_pcHit.doAttackAction();
		if (_target.isInvincible())
			return false;

		// テレポート処理中
		if (_target.isTeleport()) {
			return false;
		}
		// 攻撃される側または攻撃する側がセーフティーゾーン
		if ((_target.getZoneType() == 1) || (_attacker.getZoneType() == 1)) {
			return false;
		}

		if (_target.checkNonPvP(_target, _attacker) == true) {
			return false;
		}

		if (_pcHit.calcPcHit()) {
			calcPcPcHit();
		}
		return _isHit;
	}

	private void calcPcPcHit() {
		_hitRate = _pcHit.calcPcHitRate(_hitRate);
		L1OnPcHit oph = new L1OnPcHit(_target);
		_hitRate = oph.hitRateOnPc(_hitRate);
		_isHit = Random.chance100(_hitRate);
		L1ItemInstance weapon = _attacker.getWeapon();
		if (weapon != null) {
			if (weapon.isBow() && _isHit) {
				_isHit = calcErEvasion();
			}
			if (weapon.isKiringku()) {
				_isHit = true;
			}
		}

		if (_isHit && _target.hasSkillEffect(COUNTER_BARRIER)) {
			L1Magic magic = new L1Magic(_target, _attacker);
			if (magic.calcProbabilityMagic(COUNTER_BARRIER)) {
				boolean isCounter = false;
				if (weapon == null) {
					isCounter = true;
				} else {
					if (!weapon.isBow() && !weapon.isGauntlet()) {
						isCounter = true;
					}
				}
				if (isCounter) {
					L1Dmg counterDmg = L1Dmg.get(true, 0, _target, _attacker);
					oph.actionCounterBarrier(counterDmg);
					_isHit = false;
				}
			}
		}
	}

	// ●●●● ＥＲによる回避判定 ●●●●
	private boolean calcErEvasion() {
		int er = _target.getEr();
		int rnd = Random.nextInt(100) + 1;
		return er < rnd;
	}
}
